package com.camtc.camcenter.util;

import com.camtc.camcenter.common.CamConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * <p>
 * 异常信息处理工具类，替换 -{}-
 * </p>
 *
 * @author chentianshun
 * @since 2021-06-22
 */

@Slf4j
public class ExceptionUtil {

    /**
     * 异常信息格式
     */
    private static final String EXCEPTION_LINE_INFO = "Exception Thread[ID : {} Name : {}] - Message : {}";
    /**
     * 包名
     */
    private static final String PACTERA_PACKAGE_NAME = "com.camtc.camcenter";

    /**
     * 防止构造
     */
    private ExceptionUtil() {


    }

    /**
     * 异常信息替换，{}
     *
     * @param exceptionInfo
     * @param infos
     * @return
     */
    public static String procExceptionInfo(String exceptionInfo, String... infos) {
        if (!exceptionInfo.matches(CamConstants.CHECK_INFO_REG)) {
            return exceptionInfo;
        }
        StringBuilder rtnSb = new StringBuilder();
        Pattern pattern = compile("(?<msgInfo>.*?\\{}[^{]*)");
        Matcher matcher = pattern.matcher(exceptionInfo);
        int msgCount = 0;
        while (matcher.find()) {
            if (msgCount < infos.length - 1) {
                rtnSb.append(matcher.group("msgInfo").replaceAll("\\{}", infos[msgCount]));
                msgCount++;
            }
            msgCount++;
        }
        return rtnSb.toString();
    }

    /**
     * @param ex
     */
    public static void logExceptionInfo(Exception ex) {
        long threadId = Thread.currentThread().getId();
        String threadName = Thread.currentThread().getName();
        log.error(EXCEPTION_LINE_INFO, threadId, threadName, ExceptionUtils.getMessage(ex) + " - " + ExceptionUtils.getRootCauseMessage(ex));
    }

    /**
     * @param ex
     * @return
     */
    public static String getExceptionInfo(Throwable ex) {
        StringBuilder exceptionInfoString = new StringBuilder();
        exceptionInfoString.append(ExceptionUtils.getMessage(ex)).append(" - ").append(ExceptionUtils.getRootCauseMessage(ex));
        String[] exceptionList = ExceptionUtils.getRootCauseStackTrace(ex);
        int sourceErrorCount = 0;
        for (String s : exceptionList) {
            if (sourceErrorCount > 5) {
                break;
            }
            if (s.contains(PACTERA_PACKAGE_NAME)) {
                sourceErrorCount++;
            }
            exceptionInfoString.append(s);
        }
        return exceptionInfoString.toString();
    }

}
